package com.ankiang.treeprint.adaptor;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ankiang.treeprint.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Demo 中通用的 RecyclerView Adapter。
 * Created by sm on 2015/5/3.
 */
public class TRRecyclerViewAdapter extends RecyclerView.Adapter<TRRecyclerViewAdapter.ViewHolder> {

    private List<Data> mItems;
    private AdapterView.OnItemClickListener mOnItemClickListener;

    public TRRecyclerViewAdapter() {
        mItems = new ArrayList<>();
    }


    public void addItem(int position, int rid) {
        if (position > mItems.size()) return;

        mItems.add(position, new Data(rid));
        notifyItemInserted(position);
    }


    public void removeItem(int position) {
        if (position >= mItems.size()) return;

        mItems.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View root = inflater.inflate(R.layout.tr_image_view_item, viewGroup, false);
        return new ViewHolder(root, this);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        Data data = mItems.get(i);
        viewHolder.setImage(data.rid);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    private void onItemHolderClick(RecyclerView.ViewHolder itemHolder) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(null, itemHolder.itemView,
                    itemHolder.getAdapterPosition(), itemHolder.getItemId());
        }
    }

    public static class Data {
        public int rid;

        public Data(int rid) {
            this.rid = rid;
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mTextView;
        private TRRecyclerViewAdapter mAdapter;

        public ViewHolder(View itemView, TRRecyclerViewAdapter adapter) {
            super(itemView);
            itemView.setOnClickListener(this);

            mAdapter = adapter;

            mTextView = (ImageView) itemView.findViewById(R.id.imageView);
        }

        public void setImage(int rid) {
            mTextView.setImageResource(rid);
        }


        @Override
        public void onClick(View v) {
            mAdapter.onItemHolderClick(this);
        }
    }
}
